<template>
  <el-dialog :model-value="modelValue" :title="title" @close="handleClose">
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <el-form-item label="账号：" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="姓名：" prop="nickName">
        <el-input v-model="form.nickName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注：">
        <el-input v-model="form.note" type="textarea" :rows="4" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>

      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="onSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { addUserApi, getUserInfoByIdApi, updateUserInfoApi } from '@/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
  },
  title: {
    type: String,
  },
  editId: {
    type: Number
  }
})

const emits = defineEmits(['update:modelValue', 'update:editId'])
const initState: IAddUserParams = {
  email: '',
  nickName: '',
  note: '',
  password: '',
  username: '',
  status: 1,
}
const form = reactive<IAddUserParams>({ ...initState })

const handleClose = () => {
  emits('update:modelValue', false)
}

const rules = reactive<FormRules<typeof form>>({
  username: [
    {
      required: true, message: '请输入账号', trigger: 'blur'
    }
  ],
  nickName: [
    {
      required: true, message: '请输入姓名', trigger: 'blur'
    }
  ],
  email: [
    {
      required: true, message: '请输入邮箱', trigger: 'blur'
    },
    {
      // type 是 element 里面已经封装好的一个类型，指定里面的内容是什么
      type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'
    }
  ],
  password: [
    {
      required: true, message: '请输入密码', trigger: 'blur'
    },
    {
      min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'
    },
    {
      // pattern 是正则表达式，要求 password 要满足这个规律才通过
      pattern: /^[0-9A-Za-z]{6,20}$/, message: '密码格式不正确', trigger: 'blur'
    }
  ]
})

const formRef = ref<FormInstance | null>(null);

const onSubmit = () => {
  // 判断当前是添加还是编辑
  if (props.editId !== 0) {
    // 表单校验+确定提交，自己实现
    updateUserInfoApi(form as any as IUserModel).then(res => {
      if (res.code === 200) {
        ElMessage.success('修改成功');
        emits('update:modelValue', false)
        // 把id修改为0
        emits('update:editId', 0)
      }
    })
  } else {
    formRef.value?.validate((valid) => {
      if (valid) {
        ElMessageBox.confirm('确认添加新用户吗?', '提示', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
        }).then(() => {
          // 发请求 
          addUserApi(form).then(res => {
            if (res.code === 200) {
              // 提示
              ElMessage.success('添加成功');
              // 关闭对话框
              emits('update:modelValue', false)
              // 是否需要刷新表格里面的数据，取决于你的实际需求
            }
          })
        })
      }
    })
  }
  // 清空表单
  // formRef.value?.resetFields(); // 使用这个方式清空可以，但是是依赖于 rules 的，rules里面没有约束的数据就不会被初始化
  Object.assign(form, initState)
}

// 什么需要根据 editId 发请求获取后端的数据
// 当editId变化的时候
watch(() => props.editId, () => {
  if (props.editId !== 0) {
    getUserInfoByIdApi(props.editId as number).then(res => {
      if (res.code === 200) {
        // 把数据赋值给表单
        Object.assign(form, res.data);
      }
    })
  }
})

</script>
<style lang="less" scoped></style>